package com.lq.schoolshop.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.lq.schoolshop.bean.Result;
import com.lq.schoolshop.bean.StatusCode;
import com.lq.schoolshop.service.UserService;
import com.lq.schoolshop.util.JwtUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.rmi.server.UID;

/**
 * @Author
 * @Date2021/1/5 20:23
 * @Version V1.0
 * 拦截器，拦截每一个接口 使其检测是否带有Token 没有就拦截  有就放行
 **/
@Component
public class TokenInterceptor  implements HandlerInterceptor {
    private Logger logger = Logger.getLogger(TokenInterceptor.class);

    private static boolean isdevelop = false; //是否开发

    @Autowired
    private UserService userService;

    //拦截器需要忽略的URL
    private String ignoreURL[] = {
            "/before/login",
            "/before/loadlogoimg",
            "/before/login/",
            "/before/loadlogoimg/",
            "/before/login///",
            "/before/loadlogoimg///",
            "//before/login//",
            "//before/loadlogoimg//",
            "/before/register",
            "/before/register/",
            "/before/register//",
            "/before/complain",
            "/before/complain/",
            "/before/complainFinally",
            "/before/complainFinally/",
            "/before/VerifyToken",
            "/before/VerifyToken/"
    };


    /**
     * 进入Controller层之前拦截请求
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //解决跨域
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,OPTIONS,GET");
        //20天有效
        response.setHeader("Access-Control-Max-Age", "1728000");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        if(!isdevelop){ //不是开发
            //1.获取请求中的头部参数Token
            String url = request.getRequestURI();
            String token = request.getHeader("define-token");
            String method = request.getMethod();
            boolean isflag = true;
            System.out.println("URL:" + url + "---" + "Token:" + token + "---" + "Method:" + method);
            PrintWriter out = null;
            //2.遍历需要忽略拦截的路径  使其放行
            for (String item : ignoreURL) {
                if (item.equals(url)) {
                    System.out.println(url);
                    return true;
                }
            }

            if(token!=null && !token.equals("")){
                String userId = JwtUtil.getUserId(token);
                int uid = Integer.parseInt(userId);
                int urow = userService.selByIdAndToken(uid, token);
                if(urow>0){  //表示查到了  该用户的token 进入主页
                    System.out.println("放行");
                    Result success = new Result(false, StatusCode.OK, "Token:无效令牌或已经过期");
                    return true;
                }else {
                    System.out.println("不是一致拦截");
                    Result error = new Result(false, StatusCode.JWTERROR, "Token:无效令牌或已经过期");
                    String result = JSONObject.toJSONString(error);
                    out = response.getWriter();
                    out.append(result);
                    out.flush();
                    return false;
                }
            }else{
                System.out.println("token为null:");
                Result error = new Result(false, StatusCode.JWTERROR, "Token:无效令牌或已经过期");
                String result = JSONObject.toJSONString(error);
                out = response.getWriter();
                out.append(result);
                out.flush();
                return false;
            }
        }else{ //是开发
            return  true;
        }





    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


}
